/*
 * Copyright (C) 2010, Funcom AS, All Rights Reserved
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  @authors
 *  Svein Gunnar Larsen <sveingunnarlarsen@gmail.com>
 *  Erik Thune Lund <culex.eriklund@gmail.com>
 *  Michel Krohn-Dale <kronicz@gmail.com>
 */

package com.funcom.peeler.tool;

import com.funcom.peeler.ResourceLoader;
import com.funcom.peeler.UpdateCont;
import com.funcom.peeler.WorkBench;
import com.funcom.peeler.symbol.Symbol;
import com.jmex.bui.BButton;

import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class ToolPanel extends JFrame {
    private JPanel mainPanel;
    private JToggleButton BButtonButton;
    private JToggleButton BLabelButton;
    private JToggleButton BToggleButtonButton;
    private JToggleButton BCheckBoxButton;
    private JToggleButton BTextFieldButton;
    private JToggleButton BGeomViewButton;
    private JToggleButton BComboBoxButton;
    private JToggleButton BSliderButton;
    private JToggleButton BContainerButton;
    private JToggleButton placeholderButton;
    private JToggleButton btnSelect;
    private JToggleButton btnMark;
    private JToggleButton btnPan;
    private JToggleButton btnResize;
    private JToggleButton btnWorkspace;
    private JButton saveButton;
    private JButton openButton;
    private JToolBar toolBar;
    private ButtonGroup toolButtons;

    private static final int BUI_BUTTON_LENGTH = 10;
    private JToggleButton[] bBUIbuttonList;

    private Symbol.ToolType tool = Symbol.ToolType.SELECT;

    public ToolPanel() {
        super("Toolbox");

        setVisible(true);
        setResizable(false);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        addWindowListener( new WindowAdapter(){
            public void windowClosing( WindowEvent e){
                if(UpdateCont.get().getWorkBenches().isEmpty()) System.exit(0);

                int result = JOptionPane.showConfirmDialog(null , "Close the toolbox and all workspaces?");
                switch ( result ){
                    case JOptionPane.YES_OPTION:
                        UpdateCont.get().closeAllWorkBenches();
                        System.exit(0);
                }
            }
        });

        setJMenuBar(createMenu());

        createBUIComponents();
        createToolComponents();
        toolBar.setFloatable(false);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        getContentPane().add(mainPanel);
        pack();
        setLocation(screenSize.width - getWidth(), 0);
        UpdateCont.get().setToolbox( this );
    }

    public Symbol.ToolType getTool() {
        return tool;
    }

    private void updateWorkBenchTools() {

        for ( WorkBench workbench : UpdateCont.get().getWorkBenches() ) {
            workbench.updateTool( tool );
        }
    }

    public void setTool(Symbol.ToolType tool){
        for (int i = 0; i < bBUIbuttonList.length; i++) {
            bBUIbuttonList[i].setSelected(false);
        }
        toolButtons.clearSelection();

        switch(tool){
            case MULTI:{
                this.tool = tool;
                btnSelect.doClick();
                break;
            }
            case SELECT:{
                this.tool = tool;
                btnMark.doClick();
                break;
            }
            case PAN:{
                this.tool = tool;
                btnPan.doClick();
                break;
            }
            case RESIZE:{
                this.tool = tool;
                btnResize.doClick();
                break;
            }
        }
        updateWorkBenchTools();
    }

    private JMenuBar createMenu() {
        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                String ac = event.getActionCommand();
                if (ac.equals("Open")) {
                    UpdateCont.get().loadNewWorkBench();
                } else if (ac.equals("Exit")) {
                    int result = JOptionPane.showConfirmDialog(null, "Close the toolbox and all workspaces?");
                    switch (result) {
                        case JOptionPane.YES_OPTION:
                            UpdateCont.get().closeAllWorkBenches();
                            System.exit(0);
                            break;
                    }
                }
            }
        };
        JMenuBar menuBar = new JMenuBar();

        JMenu menu = new JMenu("File");
        JMenuItem menuItem = new JMenuItem("Open");
        menuItem.setToolTipText("CTRL + O");
        menuItem.addActionListener(listener);
        menu.add(menuItem);

        menuItem = new JMenuItem("Exit");
        menuItem.addActionListener(listener);
        menu.add(menuItem);

        menuBar.add(menu);

        final JMenuItem propFrame = new JCheckBoxMenuItem("Properties Box");
        propFrame.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                UpdateCont.get().getPropFrame().setVisible(propFrame.isSelected());
            }
        });

        final JMenu viewMenu = new JMenu("View");

        viewMenu.addMenuListener(new MenuListener() {
            public void menuSelected(MenuEvent e) {
                propFrame.setSelected( UpdateCont.get().getPropFrame() != null && UpdateCont.get().getPropFrame().isVisible() );
                viewMenu.add(propFrame);
            }

            public void menuDeselected(MenuEvent e) {
                viewMenu.removeAll();
            }

            public void menuCanceled(MenuEvent e) {
            }
        });
        menuBar.add(viewMenu);

        return menuBar;
    }

    private void createBUIComponents() {

        bBUIbuttonList = new JToggleButton[BUI_BUTTON_LENGTH];

        BButtonButton.setActionCommand("button");
        bBUIbuttonList[0] = BButtonButton;
        BToggleButtonButton.setActionCommand("toggle");
        bBUIbuttonList[1] = BToggleButtonButton;
        BLabelButton.setActionCommand("label");
        bBUIbuttonList[2] = BLabelButton;
        BCheckBoxButton.setActionCommand("checkbox");
        bBUIbuttonList[3] = BCheckBoxButton;
        BComboBoxButton.setActionCommand("combobox");
        bBUIbuttonList[4] = BComboBoxButton;
        BTextFieldButton.setActionCommand("textfield");
        bBUIbuttonList[5] = BTextFieldButton;
        BSliderButton.setActionCommand("slider");
        bBUIbuttonList[6] = BSliderButton;
        BGeomViewButton.setActionCommand("geom");
        bBUIbuttonList[7] = BGeomViewButton;
        BContainerButton.setActionCommand("panel");
        bBUIbuttonList[8] = BContainerButton;
        placeholderButton.setActionCommand("placeholder");
        bBUIbuttonList[9] = placeholderButton;

        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String ac = e.getActionCommand();

                toolButtons.clearSelection(); // Clear the toolbuttons

                if (ac.equals("button")) {
                    for (int i = 0; i < bBUIbuttonList.length; i++) {
                        if (!bBUIbuttonList[i].getActionCommand().equals("button"))
                            bBUIbuttonList[i].setSelected(false);
                    }
                    if (bBUIbuttonList[0].isSelected()) {
                        BButton button = new BButton("");
                        button.setProperty("Type", Symbol.BType.BUTTON);
                        button.setStyleClass("button");

                        UpdateCont.get().sendToWorkBench(button);
                        tool = Symbol.ToolType.PLACE;
                    } else {
                        tool = Symbol.ToolType.SELECT;
                    }
                } else if (ac.equals("toggle")) {
                    for (int i = 0; i < bBUIbuttonList.length; i++) {
                        if (!bBUIbuttonList[i].getActionCommand().equals("toggle"))
                            bBUIbuttonList[i].setSelected(false);

                    }
                    if (bBUIbuttonList[1].isSelected()) {
                        BButton toggleButton = new BButton("");
                        toggleButton.setProperty("Type", Symbol.BType.TOGGLEBUTTON);
                        toggleButton.setStyleClass("toggleButton");

                        UpdateCont.get().sendToWorkBench(toggleButton);
                        tool = Symbol.ToolType.PLACE;
                    } else {
                        tool = Symbol.ToolType.SELECT;
                    }
                } else if (ac.equals("label")) {
                    for (int i = 0; i < bBUIbuttonList.length; i++) {
                        if (!bBUIbuttonList[i].getActionCommand().equals("label"))
                            bBUIbuttonList[i].setSelected(false);
                    }
                    if (bBUIbuttonList[2].isSelected()) {
                        BButton label = new BButton("");
                        label.setProperty("Type", Symbol.BType.LABEL);
                        label.setStyleClass("label");

                        UpdateCont.get().sendToWorkBench(label);
                        tool = Symbol.ToolType.PLACE;
                    } else {
                        tool = Symbol.ToolType.SELECT;
                    }

                } else if (ac.equals("checkbox")) {
                    for (int i = 0; i < bBUIbuttonList.length; i++) {
                        if (!bBUIbuttonList[i].getActionCommand().equals("checkbox"))
                            bBUIbuttonList[i].setSelected(false);
                    }
                    if (bBUIbuttonList[3].isSelected()) {
                        BButton checkBox = new BButton("");
                        checkBox.setProperty("Type", Symbol.BType.CHECKBOX);
                        checkBox.setStyleClass("checkbox");

                        UpdateCont.get().sendToWorkBench(checkBox);
                        tool = Symbol.ToolType.PLACE;
                    } else {
                        tool = Symbol.ToolType.SELECT;
                    }
                } else if (ac.equals("combobox")) {
                    for (int i = 0; i < bBUIbuttonList.length; i++) {
                        if (!bBUIbuttonList[i].getActionCommand().equals("combobox"))
                            bBUIbuttonList[i].setSelected(false);
                    }
                    if (bBUIbuttonList[4].isSelected()) {
                        BButton combobox = new BButton("");
                        combobox.setProperty("Type", Symbol.BType.COMBOBOX);
                        combobox.setStyleClass("combobox");

                        UpdateCont.get().sendToWorkBench(combobox);
                        tool = Symbol.ToolType.PLACE;
                    } else {
                        tool = Symbol.ToolType.SELECT;
                    }
                } else if (ac.equals("textfield")) {
                    for (int i = 0; i < bBUIbuttonList.length; i++) {
                        if (!bBUIbuttonList[i].getActionCommand().equals("textfield"))
                            bBUIbuttonList[i].setSelected(false);
                    }
                    if (bBUIbuttonList[5].isSelected()) {
                        BButton textfield = new BButton("");
                        textfield.setProperty("Type", Symbol.BType.TEXTFIELD);
                        textfield.setStyleClass("textfield");

                        UpdateCont.get().sendToWorkBench(textfield);
                        tool = Symbol.ToolType.PLACE;
                    } else {
                        tool = Symbol.ToolType.SELECT;
                    }
                } else if (ac.equals("slider")) {
                    for (int i = 0; i < bBUIbuttonList.length; i++) {
                        if (!bBUIbuttonList[i].getActionCommand().equals("slider"))
                            bBUIbuttonList[i].setSelected(false);
                    }
                    if (bBUIbuttonList[6].isSelected()) {
                        BButton slider = new BButton("");
                        slider.setProperty("Type", Symbol.BType.SLIDER);
                        slider.setStyleClass("slider");

                        UpdateCont.get().sendToWorkBench(slider);
                        tool = Symbol.ToolType.PLACE;
                    } else {
                        tool = Symbol.ToolType.SELECT;
                    }
                } else if (ac.equals("geom")) {
                    for (int i = 0; i < bBUIbuttonList.length; i++) {
                        if (!bBUIbuttonList[i].getActionCommand().equals("geom"))
                            bBUIbuttonList[i].setSelected(false);
                    }
                    if (bBUIbuttonList[7].isSelected()) {
                        BButton geom = new BButton("");
                        geom.setProperty("Type", Symbol.BType.GEOMVIEW);
                        geom.setStyleClass("geomview");

                        UpdateCont.get().sendToWorkBench(geom);
                        tool = Symbol.ToolType.PLACE;
                    } else {
                        tool = Symbol.ToolType.SELECT;
                    }
                } else if (ac.equals("panel")) {
                    for (int i = 0; i < bBUIbuttonList.length; i++) {
                        if (!bBUIbuttonList[i].getActionCommand().equals("panel"))
                            bBUIbuttonList[i].setSelected(false);
                    }
                    if (bBUIbuttonList[8].isSelected()) {
                        BButton panel = new BButton("");
                        panel.setProperty("Type", Symbol.BType.CONTAINER);
                        panel.setStyleClass("panel");

                        UpdateCont.get().sendToWorkBench(panel);
                        tool = Symbol.ToolType.PLACE;
                    } else {
                        tool = Symbol.ToolType.SELECT;
                    }
                } else if (ac.equals("placeholder")) {
                    for (int i = 0; i < bBUIbuttonList.length; i++) {
                        if (!bBUIbuttonList[i].getActionCommand().equals("placeholder"))
                            bBUIbuttonList[i].setSelected(false);
                    }
                    if (bBUIbuttonList[9].isSelected()) {
                        BButton placeholder = new BButton("");
                        placeholder.setProperty("Type", Symbol.BType.PLACEHOLDER);

                        UpdateCont.get().sendToWorkBench(placeholder);
                        tool = Symbol.ToolType.PLACE;
                    } else {
                        tool = Symbol.ToolType.SELECT;
                    }
                }

                if (tool.equals(Symbol.ToolType.SELECT)) {
                    btnSelect.doClick();
                }
                updateWorkBenchTools();
            }
        };

        BButtonButton.addActionListener(listener);
        BToggleButtonButton.addActionListener(listener);
        BLabelButton.addActionListener(listener);
        BCheckBoxButton.addActionListener(listener);
        BComboBoxButton.addActionListener(listener);
        BTextFieldButton.addActionListener(listener);
        BSliderButton.addActionListener(listener);
        BGeomViewButton.addActionListener(listener);
        BContainerButton.addActionListener(listener);
        placeholderButton.addActionListener(listener);
    }

    private void createToolComponents() {

        toolButtons = new ButtonGroup();
        
        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent event) {

                //Unpressing all the BUI buttons when selecting a tool from the toolbox
                for (int i = 0; i < bBUIbuttonList.length; i++) {
                    bBUIbuttonList[i].setSelected(false);
                }
                String ac = event.getActionCommand();

                if (ac.equals("Save")) {
                    UpdateCont.get().getFocusedWorkBench().saveWorkSpace();
                    return;
                }else if(ac.equals("Load")) {
                    UpdateCont.get().loadNewWorkBench();
                    return;
                }

                if(toolButtons.getSelection().getActionCommand().equals("Select")){
                    tool = Symbol.ToolType.MULTI;
                }else if(toolButtons.getSelection().getActionCommand().equals("Mark")){
                    tool = Symbol.ToolType.SELECT;
                }else if(toolButtons.getSelection().getActionCommand().equals("Pan")){
                    tool = Symbol.ToolType.PAN;
                }else if(toolButtons.getSelection().getActionCommand().equals("Resize")){
                    tool = Symbol.ToolType.RESIZE;
                }else if(toolButtons.getSelection().getActionCommand().equals("Workspace")){
                    new WorkBench();
                    btnSelect.doClick();
                }

                if(!ac.equals("Workspace")){
                    updateWorkBenchTools();
                }
            }
        };

        btnSelect.setIcon(ResourceLoader.getInstance().getImageIcon( Symbol.ToolImage.SELECT ) );
        btnSelect.setActionCommand("Select");
        btnSelect.addActionListener(listener);
        toolButtons.add(btnSelect);

        btnMark.setIcon(ResourceLoader.getInstance().getImageIcon( Symbol.ToolImage.MARK ) );
        btnMark.setActionCommand("Mark");
        btnMark.addActionListener(listener);
        toolButtons.add(btnMark);

        btnPan.setIcon(ResourceLoader.getInstance().getImageIcon( Symbol.ToolImage.PAN ) );
        btnPan.setActionCommand("Pan");
        btnPan.addActionListener(listener);
        toolButtons.add(btnPan);

        btnResize.setIcon(ResourceLoader.getInstance().getImageIcon( Symbol.ToolImage.RESIZE ) );
        btnResize.setActionCommand("Resize");
        btnResize.addActionListener(listener);
        toolButtons.add(btnResize);

        btnWorkspace.setIcon(ResourceLoader.getInstance().getImageIcon( Symbol.ToolImage.NEW ) );
        btnWorkspace.setActionCommand("Workspace");
        btnWorkspace.addActionListener(listener);
        toolButtons.add(btnWorkspace);

        saveButton.setIcon(ResourceLoader.getInstance().getImageIcon( Symbol.ToolImage.SAVE ) );
        saveButton.setActionCommand("Save");
        saveButton.addActionListener(listener);

        openButton.setIcon(ResourceLoader.getInstance().getImageIcon( Symbol.ToolImage.LOAD ) );
        openButton.setActionCommand("Load");
        openButton.addActionListener(listener);
    }
}
